package com.example.myapplication1.ui.order;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication1.R;
import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.db.DatabaseHelper.FeedingRecord;
import com.example.myapplication1.utils.PreferenceManager;

import java.util.List;

public class OrderHistoryFragment extends Fragment {
    private RecyclerView ordersRecyclerView;
    private RecyclerView feedingRecyclerView;
    private TextView emptyOrdersView;
    private TextView emptyFeedingView;
    private TextView feedingTitleView;
    private TextView ordersTitleView;
    private OrderAdapter orderAdapter;
    private FeedingRecordAdapter feedingAdapter;
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databaseHelper = new DatabaseHelper(requireContext());
        preferenceManager = new PreferenceManager(requireContext());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_history, container, false);
        
        // 初始化视图
        initViews(view);
        
        // 设置返回按钮
        ImageButton backButton = view.findViewById(R.id.back_button);
        backButton.setOnClickListener(v -> {
            try {
                // 使用Navigation组件返回到个人中心
                Navigation.findNavController(view).navigate(R.id.action_orderHistory_to_profile);
            } catch (Exception e) {
                Log.e("OrderHistoryFragment", "导航错误：" + e.getMessage());
                // 如果导航失败，回退到上一个Fragment
                requireActivity().getSupportFragmentManager().popBackStack();
            }
        });
        
        // 设置RecyclerView
        setupRecyclerViews();
        
        // 加载数据
        loadOrders();
        loadFeedingRecords();
        
        return view;
    }

    private void initViews(View view) {
        ordersRecyclerView = view.findViewById(R.id.order_recycler_view);
        feedingRecyclerView = view.findViewById(R.id.feeding_recycler_view);
        emptyOrdersView = view.findViewById(R.id.empty_orders_view);
        emptyFeedingView = view.findViewById(R.id.empty_feeding_view);
        feedingTitleView = view.findViewById(R.id.feeding_title);
        ordersTitleView = view.findViewById(R.id.orders_title);
    }

    private void setupRecyclerViews() {
        // 设置订单RecyclerView
        ordersRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        orderAdapter = new OrderAdapter();
        ordersRecyclerView.setAdapter(orderAdapter);
        
        // 设置喂养记录RecyclerView
        feedingRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        feedingAdapter = new FeedingRecordAdapter();
        feedingRecyclerView.setAdapter(feedingAdapter);
    }

    private void loadOrders() {
        long userId = preferenceManager.getUserId();
        List<Order> orders = databaseHelper.getUserOrders(userId);
        
        if (orders.isEmpty()) {
            ordersRecyclerView.setVisibility(View.GONE);
            emptyOrdersView.setVisibility(View.VISIBLE);
        } else {
            ordersRecyclerView.setVisibility(View.VISIBLE);
            emptyOrdersView.setVisibility(View.GONE);
            orderAdapter.setOrders(orders);
        }
    }

    private void loadFeedingRecords() {
        long userId = preferenceManager.getUserId();
        Log.d("OrderHistoryFragment", "Loading feeding records for user ID: " + userId);
        
        List<FeedingRecord> feedingRecords = databaseHelper.getUserFeedingRecords(userId);
        Log.d("OrderHistoryFragment", "Retrieved " + feedingRecords.size() + " feeding records");
        
        if (feedingRecords.isEmpty()) {
            Log.d("OrderHistoryFragment", "No feeding records found, showing empty view");
            feedingRecyclerView.setVisibility(View.GONE);
            emptyFeedingView.setVisibility(View.VISIBLE);
        } else {
            Log.d("OrderHistoryFragment", "Displaying feeding records");
            feedingRecyclerView.setVisibility(View.VISIBLE);
            emptyFeedingView.setVisibility(View.GONE);
            feedingAdapter.setFeedingRecords(feedingRecords);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 